package project2.ui.game.auto;

import project2.entity.bullet.Bullet;
import project2.entity.enemy.EnemyPlane;
import project2.resources.Sounds;
import project2.ui.game.GamePlayingPanel;

public class BulletsMove {

    private final GamePlayingPanel panel;

    public BulletsMove(GamePlayingPanel panel) {
        this.panel = panel;
    }

    public void run(Bullet b) {
        if (b == null) {
            return;
        }

        b.setPosY(b.getPosY() - b.getSpeed());// 子弹位置改变

        if (b.getPosY() <= 0) {// 超过面板边界则删除掉
            panel.bullets.remove(b);
            return;
        }

        EnemyPlane enemyPlane = hitEnemyPlanes(b);// 获取命中的敌机
        if (enemyPlane != null) {
            enemyPlane.drawFighting(panel.getGameGraphics());// 绘制敌机被命中状态
            if (enemyPlane.isKilled()) {// 敌机被击毁时
                switch (enemyPlane.getEnemyType()) {
                    case SMALL_ENEMY_PLANE:
                        Sounds.smallPlaneKilledSoundPlayer.play();
                        break;
                    case BIG_ENEMY_PLANE:
                        Sounds.bigPlaneKilledSoundPlayer.play();
                        break;
                    case BOSS_ENEMY_PLANE:
                        Sounds.bossPlaneFlyingSoundPlayer.stop();
                        Sounds.bossPlaneKilledSoundPlayer.play();
                        break;
                }
                panel.score.addAndGet(enemyPlane.getKilledScore());
                panel.enemyPlanes.remove(enemyPlane);
                panel.bullets.remove(b);
                enemyPlane.drawKilled(panel.getGameGraphics());// 绘制敌机被击毁状态
            }
        }
    }

    /**
     * 获取与子弹碰撞的敌机
     */
    private EnemyPlane hitEnemyPlanes(Bullet b) {
        for (EnemyPlane enemyPlane : panel.enemyPlanes) {
            if (b.getRectangle().intersects(enemyPlane.getRectangle())) {// 边界检测
                enemyPlane.addHittedCount();// 敌机的被命中计数累加
                return enemyPlane;
            }
        }
        return null;
    }
}
